from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework import status
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
from drf_spectacular.utils import extend_schema, OpenApiParameter
from .serializers import StudentBaseSerializer, LoginSerializer
from .response import DataResponse
from .models import StudentProfile

# Create your views here.
class LoginAPIView(APIView):
    permission_classes = [AllowAny]  # 允许任何用户访问，包括未登录用户
    @extend_schema(request=LoginSerializer)
    def post(self, request):
        try:
            serializer = LoginSerializer(data=request.data)
            username = serializer.initial_data.get("username")
            password = serializer.initial_data.get("password")
            if not username or not password:
                return DataResponse(code=400, message="请提供用户名和密码", status=status.HTTP_400_BAD_REQUEST)

            user = authenticate(request, username=f"stu{username}", password=password)

            if not user:
                user = authenticate(request, username=f"{username}", password=password)
                
            if user:
                if user.username.startswith('stu'):
                    student = StudentProfile.objects.get(user__username=user.username)
                    stu = StudentBaseSerializer(student).data
                    user_info = {
                        'username': stu['student_name'],
                        'sid': stu['student_id'],
                    }
                else:
                    user_info = {
                        'username': user.username,
                        'sid': None,
                        'classname': None,
                    }
                token, created = Token.objects.get_or_create(user=user)
                return DataResponse(
                    code=200, message="登录成功", data={"token": token.key, "user": user_info}
                )
            else:
                return DataResponse(
                    code=401, message="用户名或密码错误", status=status.HTTP_401_UNAUTHORIZED
                )
        except Exception as e:
            print(e)
            return DataResponse(code=500, message="内部服务器错误", exception=e, status=status.HTTP_500_INTERNAL_SERVER_ERROR)